package main

import (
	"encoding/json"
	"fmt"
	"github.com/PuerkitoBio/goquery"
	"github.com/russross/blackfriday"
	"strings"
)

func main() {
	data := "# thinkphp生成小程序指定页面二维码扫码跳转携带参数\n`实现功能是微信扫一扫或者内嵌的扫一扫跳转生成的二维码并携带参数`\n### 一定要看 ==[小程序接口地址](https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/qr-code/wxacode.getUnlimited.html)==\n> ##### UNIAPP 中获取到扫码内的参数\n==注意获取参数是要在上面生成二维码的页面 我上面写的是 pages/user/user , 下面的代码也是在 pages/user/user 里面的onLoad中==\n需要跳转的页面: *pages/user/user*\n```js\n\t// 注意获取参数是要在上面生成二维码的页面 我上面写的是 pages/user/user , 下面的代码也是在 pages/user/user 里面的onLoad中\n\tonLoad(e) {\n\t\t// 获取二维码带过来的参数,或者内嵌扫一扫跳转过来的参数\n\t\tthat.user_en = decodeURIComponent(e.scene).split('&')[0]\n\t\tthat.user_id = decodeURIComponent(e.scene).split('&')[1].split('=')[1]\n\t},\n```"
	GetSearchIndexDataByContent("/article/xlksjdk12sdfw", "go语言的基础", data)
}

type SearchData struct {
	Body  string `json:"body"`  // 正文内容
	Slug  string `json:"slug"`  // 包含文章的id和跳转地址
	Title string `json:"title"` // 标题
}

func GetSearchIndexDataByContent(id, title string, content string) (searchDataList []SearchData) {
	dataList := strings.Split(content, "\n")
	var isCode bool = false
	var headList, bodyList []string
	var body string

	headList = append(headList, title)
	for _, s := range dataList {
		// #{1,6}
		// 判断是否为代码块
		if strings.HasPrefix(s, "```") {
			isCode = !isCode
		}
		if strings.HasPrefix(s, "#") && !isCode {
			headList = append(headList, getHeader(s))
			//if strings.TrimSpace(body) != "" {
			bodyList = append(bodyList, getBody(body))
			//}
			body = ""
			continue
		}
		body += s
	}
	bodyList = append(bodyList, getBody(body))
	ln := len(headList)
	for i := 0; i < ln; i++ {
		searchDataList = append(searchDataList, SearchData{
			Title: headList[i],
			Body:  bodyList[i],
			Slug:  id + getSlug(headList[i]),
		})
	}
	b, _ := json.Marshal(searchDataList)
	fmt.Println(string(b))
	return searchDataList
}

// 替换字符
func getHeader(head string) string {
	head = strings.ReplaceAll(head, "#", "")
	head = strings.ReplaceAll(head, " ", "")
	return head
}

func getBody(body string) string {
	// 处理 content
	unsafe := blackfriday.MarkdownCommon([]byte(body))
	// 是否存在 script 标签
	doc, _ := goquery.NewDocumentFromReader(strings.NewReader(string(unsafe)))
	return doc.Text()
}

// "slug":"/article/xlksjdk12sdfw#go语言的基础" 在跳转标题前加上#
func getSlug(title string) string {
	return "#" + title
}
